package com.richper.springcloudh2020.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class RequestFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String userName = exchange.getRequest().getQueryParams().getFirst("userName");
        if (userName == null) { //userName 为空 拦截，非法请求  --测试用 UserName不为空 拦截，非法请求
            ServerHttpResponse response = exchange.getResponse();
            //设置 响应状态码，为 不接受 NOT_ACCEPTABLE
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 过滤器加载的顺序，返回的值越小，代表这个过滤器越 先 被加载
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
